<template>
  <div id="container"></div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { getequipmentlist } from '@/api/echarts';

export default {
  name: "MapView",
  data() {
    return {
      map: null,
      markers: [],
      cluster: null,
      districtCenters: {
        // 示例城市和区中心点
        Beijing: [116.405285, 39.904989],
        Shanghai: [121.473701, 31.230416],
        Wuhan: [114.305393, 30.593099],
        Guangzhou: [113.264385, 23.129112],
        // Add more district centers as needed
      },
      subregionCenters: {
        Chaoyang: [116.450000, 39.920000],
        Haidian: [116.310000, 39.950000],
        Pudong: [121.550000, 31.220000],
        Jingan: [121.460000, 31.230000],
        Jianghan: [114.270000, 30.580000],
        Wuchang: [114.340000, 30.540000],
        Tianhe: [113.330000, 23.140000],
        Yuexiu: [113.270000, 23.130000],
        Wangjing: [116.470000, 39.990000],
        Zhongguancun: [116.310000, 39.980000],
        Shangdi: [116.320000, 40.020000],
        Lujiazui: [121.550000, 31.240000],
        NanjingRoad: [121.480000, 31.230000],
        Xintiandi: [121.480000, 31.220000],
        Hankou: [114.270000, 30.600000],
        Guanggu: [114.400000, 30.510000],
        ZhujiangNewTown: [113.330000, 23.140000],
        BeijingRoad: [113.270000, 23.130000],
        // Add more subregion centers as needed
      }
    };
  },
  created() {
    this.fetchEquipmentList();
  },
  mounted() {
    this.initAMap();
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    async fetchEquipmentList() {
      try {
        const res = await getequipmentlist({ limit: 10000000 });
        if (!this.map) return; // 确保地图已经初始化

        const markersWithLocation = await Promise.all(
          res.msg
            .filter(item => item.lat && item.lng)
            .map(async (item) => {
              try {
                const { city, district } = await this.getAddressFromLatLng([parseFloat(item.lng), parseFloat(item.lat)]);
                return {
                  position: [parseFloat(item.lng), parseFloat(item.lat)],
                  city: city || 'Unknown',
                  district: district || 'Unknown',
                };
              } catch (error) {
                console.error(`Error fetching address for point (${item.lng}, ${item.lat}):`, error);
                return null;
              }
            })
        );

        // 过滤掉未成功获取地址的点
        this.markers = markersWithLocation.filter(item => item !== null);

        // 在地图初始化后添加标记和聚合
        this.addMarkers();
      } catch (error) {
        console.error('Error fetching equipment list:', error);
      }
    },
    initAMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c", // 申请好的Web端开发者Key
        version: "2.0", // 指定要加载的 JSAPI 的版本
        plugins: ["AMap.Scale", "AMap.Geocoder"], // 需要使用的插件列表
      }).then((AMap) => {
        this.map = new AMap.Map("container", {
          viewMode: "3D", // 是否为3D地图模式
          zoom: 4, // 初始化地图级别
          center: [116.397428, 39.90923], // 初始化地图中心点位置
          mapStyle: "amap://styles/blue", // 使用高德提供的地图样式
        });

        // 添加比例尺
        this.map.addControl(new AMap.Scale());
      }).catch((e) => {
        console.log(e);
      });
    },
    getAddressFromLatLng(lnglat) {
      return new Promise((resolve, reject) => {
        if (!this.map) return reject(new Error('Map not initialized'));

        const geocoder = new AMap.Geocoder();
        geocoder.getAddress(lnglat, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            const addressComponent = result.regeocode.addressComponent;
            resolve({
              city: addressComponent.city || 'Unknown',
              district: addressComponent.district || 'Unknown',
            });
          } else {
            reject(new Error('Geocoding failed'));
          }
        });
      });
    },
    addMarkers() {
      if (this.cluster) {
        this.cluster.clearMarkers(); // 清除现有的聚合
      }

      // 根据城市和区分组数据
      const cityClusters = {};
      const districtClusters = {};

      this.markers.forEach(marker => {
        const city = marker.city;
        const district = marker.district;

        if (!cityClusters[city]) cityClusters[city] = [];
        cityClusters[city].push(marker);

        if (!districtClusters[district]) districtClusters[district] = [];
        districtClusters[district].push(marker);
      });

      // 创建城市聚合
      const cityMarkers = Object.keys(cityClusters).map(city => new AMap.Marker({
        position: this.districtCenters[city] || [116.397428, 39.90923],
        content: `<div class="amap-marker">${city} (${cityClusters[city].length})</div>`,
      }));

      // 创建区聚合
      const districtMarkers = Object.keys(districtClusters).map(district => new AMap.Marker({
        position: this.subregionCenters[district] || [116.397428, 39.90923],
        content: `<div class="amap-marker">${district} (${districtClusters[district].length})</div>`,
      }));

      // 将城市标记添加到地图
      this.addCluster(cityMarkers, { zoom: [2, 10] });

      // 将区标记添加到地图
      this.addCluster(districtMarkers, { zoom: [10, 15] });
    },
    addCluster(markers, { zoom }) {
      if (this.cluster) {
        this.cluster.clearMarkers(); // 清除现有的聚合
      }

      // 添加标记到地图
      markers.forEach(marker => marker.setMap(this.map));

      // 初始化聚合器
      this.cluster = new AMap.MarkerClusterer(this.map, markers, {
        gridSize: 80,
        zoomOnClick: true,
        styles: [{
          url: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          size: new AMap.Size(32, 32),
          anchor: new AMap.Pixel(16, 16),
          textColor: '#fff',
          textSize: 14
        }],
      });

      this.map.on('zoomchange', () => {
        const zoomLevel = this.map.getZoom();
        if (zoomLevel >= zoom[0] && zoomLevel <= zoom[1]) {
          this.cluster.setMap(this.map);
        } else {
          this.cluster.clearMarkers();
        }
      });
    }
  },
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100vh;
}
.amap-marker {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 5px;
  border-radius: 3px;
}
</style>
